/**
 * vite配置
 */
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

export default defineConfig({
  plugins: [vue(), monkeyPlugin()],
  server: {
    port: 5174,
    host: true,
  },
});

function monkeyPlugin() {
  return {
    name: "vite-plugin-monkey",
    // 在配置钩子中修改server选项
    config(config: any) {
      return {
        server: {
          open: "/@monkey/entry.user.js", // 自动打开油猴脚本
          ...config.server, // 保留用户原有配置
        },
      };
    },

    configureServer(server: any) {
      // 主入口文件
      server.middlewares.use("/@monkey/entry.user.js", (req: any, res: any) => {
        const origin = "https://www.baidu.com";
        res.setHeader("Content-Type", "application/javascript");
        res.setHeader("X-Tampermonkey-Script", "true");
        res.end(`
          // ==UserScript==
          // @name         Vite-monkey
          // @namespace    http://your-namespace/
          // @version      0.1.0
          // @description  Development script
          // @match        ${origin}/*
          // @grant        none
          // @require      https://cdn.jsdelivr.net/npm/vite@latest/dist/client/client.mjs
          // ==/UserScript==

          (function() {
            'use strict';
            console.log('Userscript loaded!');
          })();
        `);
      });
    },
  };
}
